package com.lyt.springboot.util.algorithm;


import java.util.ArrayList;
import java.util.List;

public class S30 {
    //前中后序遍历
    //返回值为int[]   这里代码逻辑有问题
    public int[] preorderTraversal (TreeNode root) {
        int[] arr0 = new int[1];
        if(root == null) {
            return arr0;
        }
        int[] arr = {root.val};
        System.arraycopy(arr,0,arr0,0,arr.length);
        int[] left = preorderTraversal(root.left);
        int[] right = preorderTraversal(root.right);
        System.arraycopy(left,0,arr0,arr0.length-1,left.length);
        System.arraycopy(right,0,arr0,arr0.length-1,right.length);
        return arr0;
    }

    //返回值为list
    public List<Integer> preorderTraversal1 (TreeNode root) {
        List<Integer> list = new ArrayList<>();
        if(root == null) {
            return list;
        }
        list.add(root.val);
        list.addAll(preorderTraversal1(root.left));
        list.addAll(preorderTraversal1(root.left));
        return list;
    }

    //返回值为int[] 拿上的逻辑发现不行连续几次的list和int[]转换有问题
    //转换思路：不必整体来做递归
    List<Integer>list = new ArrayList<>();
    public int[] preorderTraversal2 (TreeNode root) {
        dfs(root);
        int[] arr  = new int[list.size()];
        for (int i = 0; i < list.size(); i++) {
            arr[i] = list.get(i);
        }
        return arr;
    }
    public void dfs(TreeNode root) {
        if(root !=null) {
            dfs(root.left);
            list.add(root.val);
            dfs(root.right);
        }
    }
    public class TreeNode {
    int val = 0;
    TreeNode left = null;
    TreeNode right = null;
    public TreeNode(int val) {
      this.val = val;
    }
  }

  public static void main(String[] args) {
//        String[] array = new String[]{"1","2","3","4","5","6","7","8"};
////Arrays.copyOf(array,3) 拷贝数组array里面的前3个元素
//        String[] arrayOfCopy = Arrays.copyOf(array,3);
//        String[] strings = Arrays.copyOfRange(array, 1, 5);
//        System.out.println(Arrays.toString(arrayOfCopy));
//        System.out.println(Arrays.toString(strings));
    }
}
